package com.zq.im.retrofit;

import android.content.Context;
import android.content.Intent;

import com.zq.im.App;
import com.zq.im.LoginActivity;
import com.zq.im.bean.BaseModel;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 张强 869518570@qq.com on 2020/8/27
 */
public abstract class BaseCallBack<T> implements Callback<BaseModel<T>> {


    @Override
    public void onResponse(Call<BaseModel<T>> call, Response<BaseModel<T>> response) {
        BaseModel<T> body = response.body();
        if (body == null) {
            ResponseBody errorBody = response.errorBody();
            onFailure(new Throwable(errorBody.toString()));
            return;
        }

        if (body.getCode() == 10001) {
            //跳转到登录页面 重新登录
            Context applicationContext = App.getInstances().getApplicationContext();
            Intent intent = new Intent(applicationContext, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("action", "token_expire");
            applicationContext.startActivity(intent);

        } else if (body.getCode() == 0) {
            onSuccess(response.body().getData());
        } else if (body.getCode() == 500) {
            onFailure(new Exception(body.getMsg()));
        }


    }

    @Override
    public void onFailure(Call<BaseModel<T>> call, Throwable t) {
        onFailure(t);
    }

    public abstract void onSuccess(T bean);

    public abstract void onFailure(Throwable t);


}
